<?php


class Admini_ManagebuyshopController extends Uuch_ManageController {

    public function init() {
        parent::init();
        $this->appendCss('/css/home/warehouse.css');
        $this->appendCss('/admins/css/common.css');
        
        $this->appendScript('/admins/js/jquery/jquery-1.7.2.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')->appendScript('/js/uuch.js');

        
        $this->view->type = 'buyshop';
        $this->view->countorder = Application_Model_Order::countorder(1, NULL);
        $this->view->countorder1 = Application_Model_Order::countorder(NULL, Application_Model_Order::STATUS_PAID);          //代受理
        $this->view->countorder2 = Application_Model_Order::countorder(NULL, Application_Model_Order::STATUS_CONFRIM);       //待下单
        $this->view->countorder3 = Application_Model_Order::countorder(NULL, Application_Model_Order::STATUS_UNSEND);        //待发货
        $this->view->countorder4 = Application_Model_Order::countorder(NULL, Application_Model_Order::STATUS_SELLER_SENDED); //待入库
        $this->view->countorder6 = Application_Model_Order::countorder(NULL, Application_Model_Order::STATUS_SUBSCRIBE);        //预订
        $this->view->countorder21 = Application_Model_Order::countorder(null, Application_Model_Order::STATUS_CONFRIM,1); //自己受理的
        $this->view->countorder31 = Application_Model_Order::countorder(null, Application_Model_Order::STATUS_OUTTIME_UNSEND); //超期未发货
        $this->view->countorder41 = Application_Model_Order::countorder(null, Application_Model_Order::STATUS_OUTTIME_INSTORE); //超期未收货
        $this->view->countorder77 = Application_Model_Order::countorder(2, null); //异常
        $this->view->countorder88 = Application_Model_Order::countorder(null, null, null, 3); //问题
    }

    public function indexAction() {
        $this->setTitle("代购管理");
        $pagesize = 10;
        $pageindex = $this->_getParam('start');
        if (!$pageindex) {
            $pageindex = 0;
        }
        $quick = $this->getSafeParam('quick');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $status = $this->getSafeParam('status');
        $stus = $this->getSafeParam('stus');
        $day = $this->getSafeParam("day");
        $single = $this->getSafeParam("single");
        $isdelete = $this->getSafeParam("isdelete");
        $stype = 99;
        $myorder = $this->getSafeParam("myorder");
        $problem = $this->getSafeParam("problem");
        $seltime = $this->getSafeParam("seltime");
        $taobaoname = $this->getSafeParam("taobaoname");
        if ($stus != '') {
            $status = $stus;
            $stype = $stus;
        }
        if ($day == 1) {
            $stype = 100;
        }
        if ($problem == 3) {
            $stype = 88;
        }
        if ($problem == 1) {
            $stype = 77;
        }
        if ($isdelete == 1) {
            $stype = 66;
        }
        if ($myorder == 1) {
            $stype = 21;
            $myorder = Uuch_Util::getUserNikeName();
        }
        $orderSearch = new Application_Model_Filter_OrderSearch();
        $orderSearch->quick = $quick;
        $orderSearch->starttime = $starttime;
        $orderSearch->endtime = $endtime;
        $orderSearch->status = $status;
        $orderSearch->day = $day;
        $orderSearch->myorder = $myorder;
        $orderSearch->single = $single;
        $orderSearch->problem = $problem;
        $orderSearch->isdelete = $isdelete;
        $orderSearch->seltime = $seltime;
        $orderSearch->taobaoname = $taobaoname;
        $result = Application_Model_Order::getByPages($orderSearch, $pagesize, $pageindex);
        $this->view->result = $result;
        $this->view->buydetail = $result['list'];
        $this->view->quick = $quick;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->status = $status;
        $this->view->arrsta = Application_Model_Order::getStatusList();
        $this->view->taobaoAll = Application_Model_Taobaoapi::byUserAll();
        $this->view->day = $day;
        $this->view->myorder = $myorder;
        $this->view->stype = $stype;
        $this->view->single = $single;
        $this->view->problem = $problem;
        $this->view->isdelete = $isdelete;
        $this->view->seltime = $seltime;
        $this->view->taobaoname = $taobaoname;
        $this->view->expresscomp = Application_Model_shipType::getAll('word');
    }

    /**
     * 订单详情
     */
    public function buydetailAction() {
        $this->setTitle("代购详情");
        $this->appendCss('/admins/css/yundan.css');
        $id = $this->_getParam('id');
        $result = Application_Model_Order::load($id);
        $this->view->statusAll = Application_Model_Order::getStatusAll();
        $this->view->order = $result;
        $this->view->expresscomp = Application_Model_shipType::getAll('word');
        $this->view->tracklog = Application_Model_Tracking::getAllByObjectTypeId(Application_Model_DomainobjectType::ObjectType_Order, $id);
    }
    
    public function getingexpressAction() {
        $id = $this->getSafeParam('id');
        $order = Application_Model_order::load($id);
        $name = $order->Emmis->Name;
        $no = $order->logisticsNo;
        $cemskind = mb_convert_encoding(urldecode($name), 'GB2312', 'UTF-8');
        $cemskind = urlencode($cemskind);
        $niuMen = new Uuch_Express_NiuMen($cemskind, $no);
        $content = $niuMen->getTrackData();
        $this->json(array('content' => $content));
    }

    /**
     * 代购购买
     */
    public function buyshopAction() {
        $id = $this->_getParam('id');
        $result = Application_Model_Order::load($id);
        if ($result->status == Application_Model_Order::ACCEPT) {
            if ($this->_getParam('motion') == 'buyprocure') {
                $procureId = $this->_getParam('procureId');
                $dateProcure = $this->_getParam('dateProcure');
                $idlist = $this->_getParam('idlist');
                if ($procureId != '') {
                    //修改代购订单
                    $result->procureNo = $procureId;
                    $result->dateProcure = $dateProcure == '' ? date('Y-m-d H:i:s') : $dateProcure;
                    $result->status = Application_Model_Order::UNSEND;
                    if ($idlist != '') {
                        $arrid = explode(',', $idlist);
                        foreach ($arrid as $key => $val) {
                            if ($val != '') {
                                //修改商品信息备注
                                $orderitem = Application_Model_OrderItem::load($val);
                                $orderitem->comment = $orderitem->comment . "<br>(该商品已经无货，金额已退还)";
                                //退还金额
                                $accountitem = Application_Model_UserAccount::getByUserId($result->userId);
                                if (!$accountitem) {
                                    $accountitem = new Application_Model_UserAccount();
                                }
                                $beforeMoney = $accountitem->money;
                                $accountitem->money = $accountitem->money + ($orderitem->price * $orderitem->quantity);
                                $afterMoney = $accountitem->money;
                                //添加金额日志
                                $history = new Application_Model_UserAccountHistory(); //添加记录
                                $history->type = 1;
                                $history->beforeMoney = $beforeMoney;
                                $history->afterMoney = $afterMoney;
                                $history->comment = '代购订单' . $result->orderid . '中的商品号' . $val . '无货的退还费';
                                $history->relaseId = $orderid->id;
                                $history->dateCreated = date("Y-m-d H:i:s");
                                $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                                $history->accountId = $result->userId;
                                $orderitem->save(); //保存商品信息表
                                $accountitem->save(); //保存用户金额
                                $history->save(); //保存金额日志表
                            }
                        }
                    }
                    $result->save(); //保存代购订单表
                    $this->view->ma = 1;
                } else {
                    $this->view->ma = 4;
                }
            }
        } else {
            $this->view->ma = 2;
        }
        $this->view->result = $result;
    }

    /**
     * 发货
     */
    public function shopoutAction() {
        $id = $this->_getParam('id');
        $result = Application_Model_Order::load($id);
        if ($result->status == Application_Model_Order::UNSEND) {
            if ($this->_getParam('motion') == 'buyprocure') {
                $logistics = $this->_getParam('logistics');
                $logisticsNo = $this->_getParam('logisticsNo');
                if ($logistics != '' && $logisticsNo != '') {
                    $result->logistics = $logistics;
                    $result->logisticsNo = $logisticsNo;
                    $result->status = Application_Model_Order::SELLER_SENDED;
                    $result->save();
                    $this->view->ma = 1;
                } else {
                    $this->view->ma = 4;
                }
            }
        } else {
            $this->view->ma = 2;
        }
        $this->view->result = $result;
    }

    /**
     * 代购受理
     */
    public function acceptAction() {
        $id = $this->_getParam('id');
        $result = Application_Model_Order::load($id);
        if ($result->status == Application_Model_Order::CONFRIM) {
            $result->status = Application_Model_Order::ACCEPT;
            $result->dateConfrim = date('Y-m-d H:i:s');
            $result->save();
            echo 1;
        } else {
            echo 2;
        }
        exit;
    }

    /**
     * 设置状态
     */
    public function updatestatuAction() {
        $orderId = $this->_getParam('orderId');         //订单号
        $status = $this->_getParam("statu");            //状态值

        $obj = Application_Model_Order::load($orderId);
        if($status == Application_Model_Order::STATUS_UNSEND){
            if($obj->procureNo == ""){
                echo 2;
                exit;
            }
        }else{
            switch ($status) {
                case Application_Model_Order::STATUS_CONFRIM:
                    if($obj->status != Application_Model_Order::STATUS_PAID)
                    {
                        echo 0;
                        exit;
                    }
                    break;
                case Application_Model_Order::STATUS_UNSEND:
                    if($obj->status != Application_Model_Order::STATUS_CONFRIM)
                    {
                        echo 0;
                        exit;
                    }
                    break;
                case Application_Model_Order::STATUS_SELLER_SENDED:
                    if($obj->status != Application_Model_Order::STATUS_UNSEND)
                    {
                        echo 0;
                        exit;
                    }
                    break;
                case Application_Model_Order::STATUS_INSTORE:
                    if($obj->status != Application_Model_Order::STATUS_SELLER_SENDED)
                    {
                        echo 0;
                        exit;
                    }
                    break;
                default:
                    echo 0;
                    exit;
                    break;
            }
        }
        $obj->status = $status;
        $obj->save();
        Application_Model_Operate::addOperate(0, null, $obj->getOrderNum(), "修改代购订单状态为：".Application_Model_Order::getStatusDescription($status), $obj->userId);
        echo 1;
        exit;
    }

    /**
     * 提交代购商品说明
     */
    public function updateorderitemcommentAction() {
        $id = $this->_getParam('id');                       //订单号
        $comment = $this->_getParam("comment");             //状态值

        $obj = Application_Model_OrderItem::load($id);
        $obj->description = $comment;
        $obj->save();
        $result = Application_Model_Order::load($obj->orderId);
        Application_Model_Operate::addOperate(0, null, $result->getOrderNum(), "为代购订单中的商品添加备注", $result->userId);
        echo 1;
        exit;
    }

    /**
     * 更新物流信息
     */
    public function updatelogisticsAction() {
        $id = $this->_getParam('id');                           //订单号
        $procureNo = $this->getSafeParam("procureNo");                 //淘宝号
        $logistics = $this->_getParam("logistics");             //物流公司
        $logisticsNo = $this->_getParam("logisticsNo");          //物流号
        
        if($logisticsNo != ""){
            if($procureNo != ""){
                $isTrue = Application_Model_Order::getIsTrueByIdProcureNo($id,$procureNo);
                if($isTrue){
                    echo 2;exit;
                }
            }
            $orderItem = Application_Model_Order::bylogistics($logisticsNo);
            if($orderItem){
                if($orderItem->id != $id){
                    echo 2;
                    exit;
                }
            }
            $obj = Application_Model_Order::load($id);
            if($obj->procureNo == ""){
                if($obj->operator != Uuch_Util::getUserNikeName()){
                    echo 3;
                    exit;
                }
            }
            $obj->procureNo = $procureNo;
            $obj->logistics = $logistics;
            $obj->logisticsNo = $logisticsNo;
            $obj->save();
            Application_Model_Operate::addOperate(0, null, $obj->getOrderNum(), "更新代购订单的订单号", $obj->userId);
            echo 1;
        }else{
            if($procureNo != ""){
                $isTrue = Application_Model_Order::getIsTrueByIdProcureNo($id,$procureNo);
                if($isTrue){
                    echo 2;exit;
                }
            }
            $obj = Application_Model_Order::load($id);
            if($obj->operator != Uuch_Util::getUserNikeName()){
                echo 3;
                exit;
            }
            $obj->procureNo = $procureNo;
            $obj->dateConfrim = date("Y-m-d H:i:s");
            $obj->save();
            Application_Model_Operate::addOperate(0, null, $obj->getOrderNum(), "更新代购订单的物流单号", $obj->userId);
            echo 1;
        }
        exit;
    }

    /**
     * 单个商品退款
     */
    public function singleretuenmoneyAction() {
        $id = $this->_getParam('id');                           //订单号
        $userid = $this->_getParam('userid');
        $num = $this->_getParam("num");
        $ret = Application_Model_OrderItem::singleRetuenMoney($id, $userid,$num);
        echo $ret;
        exit;
    }

    /**
     * 整个单退款
     */
    public function retuenmoneyAction() {
        $id = $this->_getParam('id');                           //订单号
        $userid = $this->_getParam('userid');

        $ret = Application_Model_Order::retuenMoney($id, $userid);
        if($ret != 0){
            $this->json(array('status'=>1,'resj'=>$ret));
        }else{
            $this->json(array('status'=>0));
        }
    }

    /**
     * 获取说明(comment)
     */
    public function getcommentAction() {
        $id = $this->_getParam('id');
        $obj = Application_Model_OrderItem::load($id);
        if ($obj)
            echo $obj->description;
        else
            echo "";
        exit;
    }
    
    public function gettaobaoAction()
    {
        $tid = $this->_getParam('tid');
        $taobao = new Uuch_Reader_TaobaoReader();
        $result = $taobao->taobaowlxx($tid);
        if($result->code == 26){
            $this->json(array("zt" =>2));
        }else{
            foreach ($result->trade->orders->order->logistics_company as $key => $nameval){
                $lname = $nameval;
            }
           $shipresult = Application_Model_shipType::getByName($lname);
           if($shipresult){

               $this->json(array("zt" =>1,'logisticsName'=>$shipresult->id,'logistics'=>$result->trade->orders->order->invoice_no)); 
           }else{
               $this->json(array("zt" =>2,'logisticsName'=>$result->trade->orders->order->logistics_company ,'logistics'=>$result->trade->orders->order->invoice_no));
           }
        }
    }
    public function countorderAction()
    {
        $id = $this->_getParam("id");
        $countItem = Application_Model_OrderItem::countItem($id);
        echo $countItem;exit;
    }
    public function setconfrimAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem && $orderItem->status == Application_Model_Order::STATUS_PAID){
            $orderItem->SetConfrim(Uuch_Util::getUserNikeName());
            $this->json(1);
        } else {
            $this->json(0);
        }
    }
    public function setwaitshipAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem && $orderItem->status == Application_Model_Order::STATUS_CONFRIM){
            $result = $orderItem->SetWaitShip(Uuch_Util::getUserNikeName());
            $this->json($result);
        } else {
            $this->json(0);
        }
    }
    public function setsellerAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem && ($orderItem->status == Application_Model_Order::STATUS_UNSEND || $orderItem->status == Application_Model_Order::STATUS_OUTTIME_UNSEND || $orderItem->status == Application_Model_Order::STATUS_SUBSCRIBE)){
            if($orderItem->logisticsNo == "") {
                $this->json(2);
            } else {
                $orderItem->status = Application_Model_Order::STATUS_SELLER_SENDED;
                $orderItem->save();
                Application_Model_Operate::addOperate(0, null, $orderItem->getOrderNum(), "设置代购订单的状态为：".Application_Model_Order::getStatusDescription($orderItem->status), $orderItem->userId);
                $this->json(1);
            }
        } else {
            $this->json(0);
        }
    }
    
    public function getdateshipAction()
    {
        $id = $this->getSafeParam('id');
        $obj = Application_Model_Order::load($id);
        if ($obj)
            $this->json($obj->dateShip);
        else
            $this->json("");
    }
    
    public function updateordershipdateAction()
    {
        $id = $this->getSafeParam("id");
        $dateShip = $this->getSafeParam("dateShip");
        $obj = Application_Model_Order::load($id);
        if ($obj) {
            $obj->dateShip = $dateShip;
            $obj->status = Application_Model_Order::STATUS_SUBSCRIBE;               
            $obj->save();
            Application_Model_Operate::addOperate(0, null, $obj->getOrderNum(), "设置代购订单的状态为：".Application_Model_Order::getStatusDescription($obj->status), $obj->userId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }
    
    public function setinstoreAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem && ($orderItem->status == Application_Model_Order::STATUS_SELLER_SENDED || $orderItem->status == Application_Model_Order::STATUS_OUTTIME_INSTORE )){
            $result = $orderItem->setInStore();
            $this->json($result);
        } else {
            $this->json(0);
        }
    }
    
    public function editoperatorAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem && ($orderItem->status == Application_Model_Order::STATUS_CONFRIM )){
            $userNikeName = $orderItem->operator;
            $orderItem->operator = Uuch_Util::getUserNikeName();
            $orderItem->save();
            Application_Model_Operate::addOperate(0, null, $orderItem->getOrderNum(), "更改代购订单的受理人为：".$userNikeName, $orderItem->userId);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }
    
    public function getproblemcontentAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem){
            $this->json(array("status"=>1,"problemcontent"=>$orderItem->problemContent,"problemtype" =>$orderItem->problem));
        }else{
            $this->json(0);
        }
    }

    public function addproblemcontentAction()
    {
        $id = $this->getSafeParam("id");
        $problemcontent = $this->getSafeParam("problemcontent");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem){
            $orderItem->problemContent = $problemcontent;
            $orderItem->problem = Application_Model_Order::Problem_Submit;
            $orderItem->save();
            $this->json(1);
        }else{
            $this->json(0);
        }
    }
    
    public function solveproblemAction()
    {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if($orderItem && $orderItem->problem == Application_Model_Order::Problem_Submit){
            $orderItem->problem = Application_Model_Order::Problem_Solve;
            $orderItem->save();
            $this->json(1);
        }else{
            $this->json(0);
        }
    }
    
    public function splitorderAction()
    {
        $orderId = $this->getSafeParam("id");
        $itemList = $this->getSafeParam("itemlist");
        $orderItem = Application_Model_Order::load($orderId);
        $result = $orderItem->SplitOrder($itemList);
        $this->json($result);
    }
    
    public function mergerorderAction()
    {
        $itemList = $this->getSafeParam("itemlist");
        $arrItemId = explode(",",$itemList);
        if(count($arrItemId) == 2){
            $this->json(4);
        } else {
            $orderItem = Application_Model_Order::load($arrItemId[0]);
            $result = $orderItem->MergerOrder($itemList,$arrItemId);
            $this->json($result);            
        }
    }
    
    public function problemshowAction()
    {
        $orderId = $this->getSafeParam("orderId");
        $problemItem = Application_Model_problem::byissue($orderId, Application_Model_problem::TYPE_ORDER);
        $arrProblem = array();
        if($problemItem){
            foreach ($problemItem as $key => $pbVal) {
                $arrProblem[$key]["issueetype"] = $pbVal->Issuetype;
                $arrProblem[$key]["content"] = htmlspecialchars($pbVal->Content);
                $arrProblem[$key]["dateCreated"] = $pbVal->DateCreated;
                $arrProblem[$key]["userName"] = $pbVal->User->NikeName;
                $arrProblem[$key]["userId"] = $pbVal->Userid;
            }
        }
        $this->json(array("type"=>1,"arrProblem"=>$arrProblem));
    }
    
    public function addorderpbAction()
    {
        $orderProblemId = $this->getSafeParam("orderProblemId");
        $content = $this->getSafeParam("content");
        $orderItem = Application_Model_Order::load($orderProblemId);
        if($content == "" || $content == null){
            $this->josn(2);
        } else {
            if($orderItem){
                $title = "代购订单：".$orderItem->OrderNum."出现异常。";
                Application_Model_problem::addProblem($orderItem->UserId, $orderProblemId, Application_Model_problem::TYPE_ORDER, 1, $title, $content);
                $messageItem = new Application_Model_Mail();
                $messageItem->title = $title;
                $messageItem->userId = $orderItem->UserId;
                $messageItem->type = 2;
                $messageItem->status = 0;
                $messageItem->message = $content;
                $messageItem->dateCreated = date("Y-m-d H:i:s");
                $messageItem->save();
                $orderItem->Problem = Application_Model_Order::Problem_Appear;
                $orderItem->save();
                Application_Model_Operate::addOperate(0, null, $orderItem->getOrderNum(), "标注代购订单异常", $orderItem->userId);
                $this->json(1);
            } else {
                $this->json(0);
            }
        }
    }
    
    public function solvecompleteAction()
    {
        $orderId = $this->getSafeParam("orderId");
        $orderItem = Application_Model_Order::load($orderId);
        if($orderItem && $orderItem->problem == Application_Model_Order::Problem_Appear){
            $orderItem->problem = Application_Model_Order::Problem_Complete;
            $orderItem->save();
            $this->json(1);
        } else {
            $this->json(0);
        }
    }
}
